/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, { SettingDrawer } from '@ant-design/pro-layout';
import React, { useEffect, useState } from 'react';
import { Link, connect } from 'umi';
import { Result, Button } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { getAuthorityFromRouter } from '@/utils/utils';
import logo from '../assets/logo.png';
import SuperIcon from '@/components/SuperIcon'
import db from '@/utils/localstorage';
import routeJson from '../../config/router'

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">去登录</Link>
      </Button>
    }
  />
);

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param perms
 */
function filterAsyncRouter(routes, perms) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.children) {
      tmp.children = filterAsyncRouter(tmp.children, perms)
      if (tmp.children && tmp.children.length > 0) {
        res.push(tmp)
      }
    } else {
      if (hasPermission(perms, tmp)) {
        res.push(tmp)
      }
    }
  })

  return res
}

/**
 * 通过meta.perms判断是否与当前用户权限匹配
 * @param perms
 * @param route
 */
function hasPermission(perms, route) {
  if (route.meta && route.meta.perms) {
    return perms.some(perm => route.meta.perms.includes(perm))
  } else {
    return true
  }
}


/**
 * use Authorized check all menu item
 */
const menuDataRender = menuList =>
  menuList.map(item => {
    const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
    localItem.icon = <SuperIcon type={item.icon} />
    return Authorized.check(item.authority, localItem, null);
  });

const BasicLayout = props => {
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
    menuData
  } = props;
  const [accessedRouters, setAccessedRouters] = useState([]);

  /**
   * constructor
   */
  useEffect(() => {
    let accessedRouters = [];
    let perms = db.get("permissions")
    if (typeof (perms) == 'object' && !Array.isArray(perms)) {
      perms = []
    }
    if (perms.includes('*')) {
      accessedRouters = routeJson
    } else {
      accessedRouters = filterAsyncRouter(routeJson, perms)
    }
    setAccessedRouters(accessedRouters)
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
      // dispatch({
      //   type: 'global/getMenuData'
      // });
      dispatch({
        type: 'global/queryAllProvCityDist',
      });
      dispatch({
        type: 'global/queryDictInfoByType',
      });

    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = payload => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
    authority: undefined,
  };
  const getCharCount = (str, char) => {
    var regex = new RegExp(char, 'g'); // 使用g表示整个字符串都要匹配
    var result = str.match(regex);          //match方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。
    var count = !result ? 0 : result.length;
    return count;
  }
  return (
    <>
      <ProLayout
        title='SuperCube'
        logo={logo}
        menuHeaderRender={(logoDom, titleDom) => (
          <Link to="/">
            {logoDom}
            {titleDom}
          </Link>
        )}
        postMenuData={menuData => menuData}
        onCollapse={handleMenuCollapse}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
            return defaultDom;
          }
          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        itemRender={(route, params, routes, paths) => {
          let count = getCharCount(route.path,'/');
          let path = count === 1 ? routes[1].path : route.path;
          return <Link to={path}>{route.breadcrumbName}</Link>
        }}
        menuDataRender={() => menuDataRender(accessedRouters)}
        rightContentRender={() => <RightContent />}
        {...props}
        {...settings}
      >
        <Authorized authority={authorized.authority} noMatch={noMatch}>
          {children}
        </Authorized>
      </ProLayout>
      <SettingDrawer
        settings={settings}
        onSettingChange={config =>
          dispatch({
            type: 'settings/changeSetting',
            payload: config,
          })
        }
      />
    </>
  );
};

export default connect(({ global, settings }) => ({
  collapsed: global.collapsed,
  settings,
  menuData: global.menuData
}))(BasicLayout);
